package ginHelper

import (
	"github.com/gin-gonic/gin"
	"strings"
)

func checkAndAddLeftDash(str string) string {
	hasLeftDash := strings.HasPrefix(str, "/")
	if !hasLeftDash {
		return "/" + str
	}
	return str
}

func listHandler(group *Group, baseUrl string) []interface{} {
	res := make([]interface{}, len(group.Handlers))
	i := 0
	for s, handler := range group.Handlers {
		url := group.Path + checkAndAddLeftDash(handler.Name())
		res[i] = gin.H{
			"name": s,
			"url":  "http://" + baseUrl + checkAndAddLeftDash(url),
		}
		i++
	}
	return res
}

func ListRouterApis(c *gin.Context) {
	url := c.Request.Host

	res := map[string]interface{}{}
	for s, group := range Groups {
		res[s] = gin.H{
			"description": group.Description,
			"apis":        listHandler(group, url),
		}
	}
	c.IndentedJSON(200, gin.H{
		"result": res,
	})
}
